/**
 * WebView JavaScript脚本
 * 处理VSCode WebView界面的交互逻辑
 * 
 * @author lihengtt <lihengsir@gmail.com>
 * @github https://github.com/lihengtt
 */

(function() {
    const vscode = acquireVsCodeApi();
    
    let currentConfig = null;
    let currentFiles = [];
    let currentPath = '/';
    let isAutoSyncEnabled = false;

    // DOM元素引用
    const elements = {
        configBtn: null,
        testConnectionBtn: null,
        refreshBtn: null,
        syncAllBtn: null,
        autoSyncBtn: null,
        outputBtn: null,
        createDirBtn: null,
        configStatus: null,
        currentPathSpan: null,
        filesList: null,
        statusBar: null,
        backBtn: null,
        homeBtn: null,
        breadcrumbPath: null
    };

    /**
     * 初始化界面
     */
    function initialize() {
        // 获取DOM元素
        elements.configBtn = document.getElementById('configBtn');
        elements.testConnectionBtn = document.getElementById('testConnectionBtn');
        elements.refreshBtn = document.getElementById('refreshBtn');
        elements.syncAllBtn = document.getElementById('syncAllBtn');
        elements.autoSyncBtn = document.getElementById('autoSyncBtn');
        elements.outputBtn = document.getElementById('outputBtn');
        elements.diagnosticsBtn = document.getElementById('diagnosticsBtn');
        elements.createDirBtn = document.getElementById('createDirBtn');
        elements.configStatus = document.getElementById('configStatus');
        elements.currentPathSpan = document.getElementById('currentPath');
        elements.backBtn = document.getElementById('backBtn');
        elements.homeBtn = document.getElementById('homeBtn');
        elements.breadcrumbPath = document.getElementById('breadcrumbPath');
        elements.filesList = document.getElementById('filesList');
        elements.statusBar = document.getElementById('statusBar');

        // 绑定事件监听器
        bindEventListeners();

        // 请求初始配置
        updateStatus('正在加载配置...');
    }

    /**
     * 绑定事件监听器
     */
    function bindEventListeners() {
        // 配置按钮
        elements.configBtn?.addEventListener('click', () => {
            sendMessage({ command: 'openConfig' });
        });

        // 测试连接按钮
        elements.testConnectionBtn?.addEventListener('click', () => {
            testConnection();
        });

        // 刷新按钮
        elements.refreshBtn?.addEventListener('click', () => {
            refreshFiles();
        });

        // 同步所有文件按钮
        elements.syncAllBtn?.addEventListener('click', () => {
            sendMessage({ command: 'syncAll' });
            updateStatus('正在同步所有文件...');
        });

        // 自动同步切换按钮
        elements.autoSyncBtn?.addEventListener('click', () => {
            sendMessage({ command: 'toggleAutoSync' });
        });

        // 查看日志按钮
        elements.outputBtn?.addEventListener('click', () => {
            sendMessage({ command: 'showOutput' });
        });

        // 系统诊断按钮
        elements.diagnosticsBtn?.addEventListener('click', () => {
            sendMessage({ command: 'runDiagnostics' });
            updateStatus('正在运行系统诊断...');
        });

        // 新建目录按钮
        elements.createDirBtn?.addEventListener('click', () => {
            createDirectory();
        });

        // 返回上级目录按钮
        elements.backBtn?.addEventListener('click', () => {
            sendMessage({ command: 'navigateBack' });
        });

        // 返回根目录按钮
        elements.homeBtn?.addEventListener('click', () => {
            sendMessage({ command: 'navigateHome' });
        });
    }

    /**
     * 发送消息到扩展
     * @param {object} message - 消息对象
     */
    function sendMessage(message) {
        vscode.postMessage(message);
    }

    /**
     * 更新状态栏
     * @param {string} text - 状态文本
     */
    function updateStatus(text) {
        if (elements.statusBar) {
            elements.statusBar.querySelector('.status-text').textContent = text;
        }
    }

    /**
     * 更新配置状态
     * @param {object} config - 配置对象
     * @param {boolean} hasConfig - 是否有配置
     */
    function updateConfigStatus(config, hasConfig) {
        currentConfig = config;
        
        if (elements.configStatus) {
            const statusText = elements.configStatus.querySelector('.status-text');
            if (hasConfig && config) {
                statusText.textContent = `已连接: ${config.serverInfo.username}@${config.serverInfo.host}:${config.serverInfo.port}`;
                statusText.style.color = 'var(--vscode-statusBarItem-prominentForeground)';
            } else {
                statusText.textContent = '未配置';
                statusText.style.color = 'var(--vscode-errorForeground)';
            }
        }

        // 更新按钮状态
        const buttonsDisabled = !hasConfig;
        if (elements.testConnectionBtn) elements.testConnectionBtn.disabled = buttonsDisabled;
        if (elements.refreshBtn) elements.refreshBtn.disabled = buttonsDisabled;
        if (elements.syncAllBtn) elements.syncAllBtn.disabled = buttonsDisabled;
        if (elements.createDirBtn) elements.createDirBtn.disabled = buttonsDisabled;
    }

    /**
     * 更新自动同步按钮状态
     * @param {boolean} isWatching - 是否正在监控
     */
    function updateAutoSyncButton(isWatching) {
        isAutoSyncEnabled = isWatching;
        
        if (elements.autoSyncBtn) {
            if (isWatching) {
                elements.autoSyncBtn.classList.add('active');
                elements.autoSyncBtn.textContent = '自动同步 (开)';
            } else {
                elements.autoSyncBtn.classList.remove('active');
                elements.autoSyncBtn.textContent = '自动同步 (关)';
            }
        }
    }

    /**
     * 刷新文件列表
     */
    function refreshFiles() {
        if (!currentConfig) {
            updateStatus('请先配置服务器连接');
            return;
        }
        
        sendMessage({ 
            command: 'refreshFiles',
            path: currentPath
        });
        updateStatus('正在刷新文件列表...');
    }

    /**
     * 更新文件列表
     * @param {Array} files - 文件列表
     * @param {string} path - 当前路径
     * @param {boolean} success - 是否成功
     * @param {string} error - 错误信息
     */
    function updateFilesList(files, path, success, error) {
        currentFiles = files || [];
        currentPath = path || '/';
        
        if (elements.currentPathSpan) {
            elements.currentPathSpan.textContent = currentPath;
        }

        // 更新面包屑导航
        updateBreadcrumb(currentPath);
        
        // 更新导航按钮状态
        updateNavigationButtons(currentPath);

        if (!elements.filesList) return;

        if (!success) {
            elements.filesList.innerHTML = `<div class="error-message">${error || '获取文件列表失败'}</div>`;
            updateStatus('获取文件列表失败');
            return;
        }

        if (currentFiles.length === 0) {
            elements.filesList.innerHTML = '<div class="loading">目录为空</div>';
            updateStatus('目录为空');
            return;
        }

        // 生成文件列表HTML
        let html = '';
        
        // 添加返回上级目录选项（如果不在根目录）
        if (currentPath !== '/') {
            html += createFileItemHTML({
                name: '..',
                path: getParentPath(currentPath),
                isDirectory: true,
                isParent: true
            });
        }

        // 添加文件和目录
        currentFiles.forEach(file => {
            html += createFileItemHTML(file);
        });

        elements.filesList.innerHTML = html;
        
        // 绑定文件项事件
        bindFileItemEvents();
        
        updateStatus(`共 ${currentFiles.length} 个项目`);
    }

    /**
     * 创建文件项HTML
     * @param {object} file - 文件对象
     * @returns {string} HTML字符串
     */
    function createFileItemHTML(file) {
        const icon = file.isDirectory ? '📁' : '📄';
        const sizeText = file.isDirectory ? '' : formatFileSize(file.size);
        const timeText = file.modifiedTime ? formatDate(new Date(file.modifiedTime)) : '';
        
        let actionsHTML = '';
        if (!file.isParent) {
            if (file.isDirectory) {
                actionsHTML = `
                    <button class="file-action" data-action="delete" data-path="${file.path}" data-is-dir="true" title="删除目录">
                        🗑️
                    </button>
                `;
            } else {
                actionsHTML = `
                    <button class="file-action" data-action="download" data-path="${file.path}" title="下载文件">
                        ⬇️
                    </button>
                    <button class="file-action" data-action="delete" data-path="${file.path}" data-is-dir="false" title="删除文件">
                        🗑️
                    </button>
                `;
            }
        }

        return `
            <div class="file-item" data-path="${file.path}" data-is-directory="${file.isDirectory}">
                <span class="file-icon">${icon}</span>
                <span class="file-name" title="${file.name}">${file.name}</span>
                <span class="file-size">${sizeText}</span>
                <span class="file-time">${timeText}</span>
                <div class="file-actions">
                    ${actionsHTML}
                </div>
            </div>
        `;
    }

    /**
     * 绑定文件项事件
     */
    function bindFileItemEvents() {
        // 文件项点击事件（进入目录）
        elements.filesList.querySelectorAll('.file-item').forEach(item => {
            item.addEventListener('click', (e) => {
                // 如果点击的是操作按钮，不处理
                if (e.target.classList.contains('file-action')) {
                    return;
                }
                
                const path = item.dataset.path;
                const isDirectory = item.dataset.isDirectory === 'true';
                
                if (isDirectory) {
                    navigateToPath(path);
                }
            });
        });

        // 文件操作按钮事件
        elements.filesList.querySelectorAll('.file-action').forEach(button => {
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                
                const action = button.dataset.action;
                const path = button.dataset.path;
                const isDir = button.dataset.isDir === 'true';
                
                switch (action) {
                    case 'download':
                        downloadFile(path);
                        break;
                    case 'delete':
                        deleteFile(path, isDir);
                        break;
                }
            });
        });
    }

    /**
     * 更新面包屑导航
     * @param {string} path - 当前路径
     */
    function updateBreadcrumb(path) {
        if (!elements.breadcrumbPath) return;
        
        const parts = path.split('/').filter(part => part);
        let html = '<span class="breadcrumb-item" data-path="/">根目录</span>';
        
        let currentPath = '';
        parts.forEach((part, index) => {
            currentPath += '/' + part;
            html += ` <span class="breadcrumb-separator">/</span> `;
            html += `<span class="breadcrumb-item" data-path="${currentPath}">${part}</span>`;
        });
        
        elements.breadcrumbPath.innerHTML = html;
        
        // 绑定面包屑点击事件
        elements.breadcrumbPath.querySelectorAll('.breadcrumb-item').forEach(item => {
            item.addEventListener('click', () => {
                const targetPath = item.dataset.path;
                sendMessage({ 
                    command: 'navigateToPath',
                    path: targetPath
                });
            });
        });
    }

    /**
     * 更新导航按钮状态
     * @param {string} path - 当前路径
     */
    function updateNavigationButtons(path) {
        const config = currentConfig;
        const homePath = config?.remotePath || '/';
        
        // 更新返回按钮状态
        if (elements.backBtn) {
            elements.backBtn.disabled = (path === '/' || path === homePath);
        }
        
        // 更新根目录按钮状态
        if (elements.homeBtn) {
            elements.homeBtn.disabled = (path === homePath);
        }
    }

    /**
     * 导航到指定路径
     * @param {string} path - 目标路径
     */
    function navigateToPath(path) {
        currentPath = path;
        sendMessage({ 
            command: 'refreshFiles',
            path: path
        });
        updateStatus('正在加载目录...');
    }

    /**
     * 下载文件
     * @param {string} path - 文件路径
     */
    function downloadFile(path) {
        sendMessage({ 
            command: 'downloadFile',
            path: path
        });
        updateStatus('正在下载文件...');
    }

    /**
     * 删除文件
     * @param {string} path - 文件路径
     * @param {boolean} isDirectory - 是否为目录
     */
    function deleteFile(path, isDirectory) {
        const fileName = path.split('/').pop();
        const confirmMessage = isDirectory ? 
            `确定要删除目录 "${fileName}" 及其所有内容吗？` :
            `确定要删除文件 "${fileName}" 吗？`;
        
        if (confirm(confirmMessage)) {
            sendMessage({ 
                command: 'deleteFile',
                path: path,
                isDirectory: isDirectory
            });
            updateStatus(`正在删除${isDirectory ? '目录' : '文件'}...`);
        }
    }

    /**
     * 测试SSH连接
     * @author lihengtt <lihengsir@gmail.com>
     */
    function testConnection() {
        if (!currentConfig) {
            updateStatus('请先配置服务器连接');
            return;
        }
        
        sendMessage({ command: 'testConnection' });
        updateStatus('正在测试SSH连接...');
        
        // 禁用测试连接按钮，防止重复点击
        if (elements.testConnectionBtn) {
            elements.testConnectionBtn.disabled = true;
            elements.testConnectionBtn.textContent = '测试中...';
        }
    }

    /**
     * 创建目录
     */
    function createDirectory() {
        const dirName = prompt('请输入目录名称:');
        if (dirName && dirName.trim()) {
            const newPath = currentPath === '/' ? 
                `/${dirName.trim()}` : 
                `${currentPath}/${dirName.trim()}`;
            
            sendMessage({ 
                command: 'createDirectory',
                path: newPath
            });
            updateStatus('正在创建目录...');
        }
    }

    /**
     * 获取父级路径
     * @param {string} path - 当前路径
     * @returns {string} 父级路径
     */
    function getParentPath(path) {
        if (path === '/') return '/';
        const parts = path.split('/').filter(p => p);
        parts.pop();
        return parts.length === 0 ? '/' : '/' + parts.join('/');
    }

    /**
     * 格式化文件大小
     * @param {number} bytes - 字节数
     * @returns {string} 格式化后的大小
     */
    function formatFileSize(bytes) {
        if (!bytes) return '';
        
        const units = ['B', 'KB', 'MB', 'GB'];
        let size = bytes;
        let unitIndex = 0;
        
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }
        
        return `${size.toFixed(1)} ${units[unitIndex]}`;
    }

    /**
     * 格式化日期
     * @param {Date} date - 日期对象
     * @returns {string} 格式化后的日期
     */
    function formatDate(date) {
        if (!date) return '';
        
        const now = new Date();
        const diff = now.getTime() - date.getTime();
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) {
            return date.toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
        } else if (days < 7) {
            return `${days}天前`;
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    }

    // 监听来自扩展的消息
    window.addEventListener('message', event => {
        const message = event.data;
        
        switch (message.command) {
            case 'updateConfig':
                updateConfigStatus(message.config, message.hasConfig);
                updateAutoSyncButton(message.isWatching);
                updateStatus('配置已更新');
                break;
                
            case 'updateFiles':
                updateFilesList(message.files, message.currentPath, message.success, message.error);
                break;
                
            case 'downloadResult':
                if (message.success) {
                    updateStatus(`文件下载成功: ${message.path.split('/').pop()}`);
                } else {
                    updateStatus('文件下载失败');
                }
                break;
                
            case 'uploadResult':
                if (message.success) {
                    updateStatus(`文件上传成功: ${message.localPath.split('/').pop()}`);
                } else {
                    updateStatus(`文件上传失败: ${message.error || '未知错误'}`);
                }
                break;
                
            case 'deleteResult':
                if (message.success) {
                    updateStatus(`删除成功: ${message.path.split('/').pop()}`);
                } else {
                    updateStatus('删除失败');
                }
                break;
                
            case 'createDirectoryResult':
                if (message.success) {
                    updateStatus(`目录创建成功: ${message.path.split('/').pop()}`);
                } else {
                    updateStatus('目录创建失败');
                }
                break;
                
            case 'syncAllResult':
                if (message.success) {
                    updateStatus('所有文件同步完成');
                } else {
                    updateStatus(`同步失败: ${message.error || '未知错误'}`);
                }
                break;
                
            case 'testConnectionResult':
                // 恢复测试连接按钮状态
                if (elements.testConnectionBtn) {
                    elements.testConnectionBtn.disabled = false;
                    elements.testConnectionBtn.textContent = '测试连接';
                }
                
                if (message.success) {
                    updateStatus('SSH连接测试成功');
                } else {
                    updateStatus(`SSH连接测试失败: ${message.error || '未知错误'}`);
                }
                break;
                
            case 'updateAutoSyncStatus':
                // 更新自动同步按钮状态
                updateAutoSyncButton(message.isWatching);
                updateStatus(message.isWatching ? '自动同步已启用' : '自动同步已禁用');
                break;
                
            case 'toggleAutoSyncError':
                // 处理自动同步切换错误
                updateStatus(`自动同步切换失败: ${message.error || '未知错误'}`);
                break;
                
            case 'updateStatus':
                // 处理状态更新消息
                updateStatus(message.message);
                break;
        }
    });

    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize);
    } else {
        initialize();
    }
})();